﻿using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Util
{
    public class FileTool
    {

        /// <summary>
        /// 获取文件编码
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public Encoding GetEncoding(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            Encoding r = GetType(fs);
            fs.Close();
            return r;
        }

        /// <summary>
        /// 通过给定的文件流，判断文件的编码类型
        /// </summary>
        /// <param name=“fs“>文件流</param>
        /// <returns>文件的编码类型</returns>
        public Encoding GetType(Stream fs)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM
            Encoding reVal = Encoding.Default;

            BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
            int i;
            int.TryParse(fs.Length.ToString(), out i);
            byte[] ss = r.ReadBytes(i);
            if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
            {
                reVal = Encoding.UTF8;
            }
            else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
            {
                reVal = Encoding.BigEndianUnicode;
            }
            else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
            {
                reVal = Encoding.Unicode;
            }
            r.Close();
            return reVal;
        }

        /// <summary>
        /// 判断是否是不带 BOM 的 UTF8 格式
        /// </summary>
        /// <param name=“data“></param>
        /// <returns></returns>
        private bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1; //计算当前正分析的字符应还有的字节数
            byte curByte; //当前分析的字节.
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        //判断当前
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X
                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("非预期的byte格式");
            }
            return true;
        }

        /// <summary>
        /// 读取文本
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>文件文本</returns>
        public string ReadFileText(string filePath)
        {
            //文件不存在,直接返回null
            if (!File.Exists(filePath))
            {
                return null;
            }
            string text = null;
            using (StreamReader sr = new StreamReader(filePath, GetEncoding(filePath)))
            {
                text = sr.ReadToEnd();
            }
            return text;
        }

        /// <summary>
        /// 写入文本文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="text"></param>
        public void TextToFile(string filePath, string text)
        {
            //存放文件的文件夹不存在则创建该文件夹,防止异常
            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }
            using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                sw.WriteLine(text);
            }
        }

        /// <summary>
        /// 追加到文本文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="text"></param>
        public void AppendTextToFileNewLine(string filePath, string text)
        {
            //存放文件的文件夹不存在则创建该文件夹,防止异常
            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }
            using (StreamWriter sw = new StreamWriter(filePath, true, Encoding.UTF8))
            {
                sw.WriteLine(text);
            }
        }

        /// <summary>
        /// FileStream读取文件文本
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string FSReadFileText(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return null;
            }
            string text = null;
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read))
            {
                byte[] b = new byte[fs.Length];
                int cnt, m;
                m = 0;
                cnt = fs.ReadByte();
                while (cnt != -1)
                {
                    b[m++] = Convert.ToByte(cnt);
                    cnt = fs.ReadByte();
                }
                text = GetEncoding(filePath).GetString(b);
            }
            return text;
        }

        /// <summary>
        /// FileStream写入文件
        /// 默认存储编码为:UTF-8
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="text">文件内容</param>
        public void FSTextToFile(string filePath, string text)
        {
            //存放文件的文件夹不存在则创建该文件夹,防止异常
            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(text);
                fs.Write(buffer, 0, buffer.Length);
            }
        }

        /// <summary>
        /// FileStream追加写入文件
        /// 默认存储编码为:UTF-8
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="text">文件内容</param>
        public void FSAppendTextToFile(string filePath, string text)
        {
            //存放文件的文件夹不存在则创建该文件夹,防止异常
            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }
            using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(text);
                //fs.Position = fs.Length;
                fs.Write(buffer, 0, buffer.Length);
            }
        }

    }
}
